package com.spc.car.data.service.project.impl;

import com.spc.car.common.exception.CustomException;
import com.spc.car.common.lang.UUID;
import com.spc.car.common.utils.ServletUtils;
import com.spc.car.common.utils.file.FileUploadUtils;
import com.spc.car.common.utils.file.FileUtils;
import com.spc.car.common.utils.ip.IpUtils;
import com.spc.car.data.domain.htgg.vo.HtggPublishAttachVO;
import com.spc.car.data.domain.htgg.xml.node.ContractAttach;
import com.spc.car.data.entity.project.ProjectHtggPublishAttach;
import com.spc.car.data.entity.sys.SysUser;
import com.spc.car.data.mapper.project.ProjectHtggPublishAttachMapper;
import com.spc.car.data.service.project.ProjectHtggPublishAttachService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotBlank;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 合同公告发布关联附件表 服务实现类
 * </p>
 *
 * @author 
 * @since 2020-04-14
 */
@Service
public class ProjectHtggPublishAttachServiceImpl extends ServiceImpl<ProjectHtggPublishAttachMapper, ProjectHtggPublishAttach> implements ProjectHtggPublishAttachService {

    @Override
    public List<ContractAttach> listAttachByContractUuid(@NotBlank String contractUuid) {
        return baseMapper.listAttachByContractUuid(contractUuid);
    }

    @Override
    @Transactional
    public void upload(MultipartFile multipartFile, String filePath, String contractUUID, SysUser sysUser) {

        String fileName = multipartFile.getOriginalFilename();
        String path = filePath + "/" + sysUser.getUserId() + "/" + String.format("%09d", sysUser.getUserId()) + "" +
                System.nanoTime() + fileName.substring(fileName.indexOf("."));

        HtggPublishAttachVO attachVO = new HtggPublishAttachVO();
        attachVO.setContractUuid(contractUUID);
        attachVO.setAttachName(FileUtils.getFileNameNoEx(fileName));
        attachVO.setAttachFileSize((int) (multipartFile.getSize() / 1024));
        attachVO.setAttachFileType(fileName.substring(fileName.indexOf(".") + 1));
        attachVO.setDownloadUrl(IpUtils.getIpAddr(ServletUtils.getRequest()) + path);

        ProjectHtggPublishAttach publishAttach = new ProjectHtggPublishAttach();
        publishAttach.setUuid(UUID.fastUUID().toString());
        publishAttach.setCreateTime(new Date());
        BeanUtils.copyProperties(attachVO, publishAttach);

        saveOrUpdate(publishAttach);
        try {
            FileUploadUtils.save(path , multipartFile);
        } catch (Exception ex) {
            ex.getStackTrace();
            throw new CustomException("文件上传失败");
        }
    }

}
